package de.koller.worlders.engine.entity.mo;

import de.koller.oceanFramework.util.ColorIntUtil;
import de.koller.oceanFramework.util.Stat;
import de.koller.worlders.engine.entity.mo.phsics.PhysicsMO;

abstract public class AbstractPlayer extends PhysicsMO {
	
	public final long DEATH_TIME = 2000;

	private final Stat walkSpeed = new Stat();
	private final Stat jumpSpeed = new Stat();
	private boolean jumpAbility = true;

	private long nextRespawn = -1;
	
	public AbstractPlayer( float x, float y, float w, float h ) {
		super( x, y, w, h );
		walkSpeed.getValues().put( "default", 0.00495 );
		jumpSpeed.getValues().put( "default", 0.00991 );
	}

	@Override
	protected void init() {
		super.init();
	
		this.setOverlapResolver( true );
	}

	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		respawn();
	}
	
	private void respawn() {
		if( this.isDeath() == false )
			return;
		
		assert this.mostate.isGameplayAffected();
		
		if( nextRespawn > wroot.getTime() ) {
			float v = nextRespawn - wroot.getTime();
			v /= (float)DEATH_TIME;
			int r = (int)(v * 255f);
			this.setTextureColor( ColorIntUtil.getIntColor( 0xff, 0xff, r, r ) );
			return;
		}
		
		reset();
	}
	
	@Override
	public void setDeath( boolean death ) {
		super.setDeath( death );
		
		if( death )
			nextRespawn = wroot.getTime() + DEATH_TIME;
	}
	
	public boolean walk( int a ) {
		return walk( a, 0 );
	}
	
	public boolean walk( float horizontal, float vertical ) {
		if( this.isDeath() )
			return false;
		
		this.getVelocity().setX( horizontal*this.getWalkSpeed().value() );
		this.getVelocity().setY( vertical*this.getWalkSpeed().value() );
		return true;
	}
	
	public boolean jump() {
		if( this.isDeath() )
			return false;
		
		if( !this.hasJumpAbility() )
			return false;
		if( !this.isBottomContact() )
			return false;
		
		double jv = this.getJumpSpeed().value();
		this.getEnergy().setY( this.getForce().getY() > 0 ? -jv : jv );
		this.setBottomContact( false );
		return true;
	}
	
	public boolean norming() {
		if( this.isDeath() )
			return false;
		
		//this.getForce().set( 0, MovingObject.GRAVITY );
		this.mostate.setGravityInversed( false );
		return true;
	}

	public void reset() {
		this.setTextureColor( 0xffffffff );
		this.setDeath( false );
		float x = wroot.getEntityContainer().getReseter().getXf() + ((1f - this.getSize().getXf()) / 2);
		float y = wroot.getEntityContainer().getReseter().getYf() + ((1f - this.getSize().getYf()) / 2);
		this.moveTo( x, y );
//		this.getForce().set( 0, GRAVITY );
		this.mostate.setGravityInversed( false );
		
		wroot.gameReset();
	}
	
	public Stat getWalkSpeed() {
		return walkSpeed;
	}

	public boolean hasJumpAbility() {
		return jumpAbility;
	}

	public Stat getJumpSpeed() {
		return jumpSpeed;
	}

}
